package org.teremail.delivery;

import java.io.IOException;
import java.util.concurrent.Callable;

import org.teremail.MailSystemException;
import org.teremail.message.FooContentHandler;
import org.teremail.message.Message;
import org.teremail.panto.MimeParser;
import org.teremail.store.Store;
import org.teremail.tx.TxRunner;

/**
 * A message handler that parses the message into to Mime if required.
 * 
 * @author Michael Barker
 *
 */
public class MimeParserHandler implements MessageHandler {

    private final Store store;
    private final MessageHandler next;
    private final TxRunner txr;
    
    public MimeParserHandler(TxRunner txr, Store store, MessageHandler next) {
        this.store = store;
        this.next = next;
        this.txr = txr;
    }
    
    public void handle(Envelope envelope) {
        
        if (envelope.getMessage().isMultipart()) {
            Message m = parseMultipart(envelope.getMessage());
            next.handle(envelope.setMessage(m));
        } else {
            next.handle(envelope);
        }
    }

    private Message parseMultipart(final Message message) {
        
        return txr.required(new Callable<Message>() {

            public Message call() {
                FooContentHandler ch = new FooContentHandler(store);
                MimeParser mp = new MimeParser();
                mp.setContentHandler(ch);
                
                InputStreamVisitor isv = new InputStreamVisitor(store);
                message.accept(isv);
                try {
                    mp.parse(isv.getInputStream());
                } catch (IOException e) {
                    throw new MailSystemException(e);
                }
                return ch.getMessage();
            }
            
        });
    }

}
